Loop Structures

For Loop


In [1]:
for n in range(10):
    print(n)


0
1
2
3
4
5
6
7
8
9

In [2]:
for fruit in ['apple', 'banana', 'orange']:
    print(fruit)


apple
banana
orange

In [3]:
from string import ascii_letters, ascii_lowercase, ascii_uppercase

In [4]:
for letter in ascii_letters:
    print(letter, end=' ')


a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 

In [5]:
for n, letter in enumerate(ascii_lowercase):
    print("{}:{}".format(n, letter), end=' ')


0:a 1:b 2:c 3:d 4:e 5:f 6:g 7:h 8:i 9:j 10:k 11:l 12:m 13:n 14:o 15:p 16:q 17:r 18:s 19:t 20:u 21:v 22:w 23:x 24:y 25:z 

In [6]:
for letter, LETTER in zip(ascii_lowercase, ascii_uppercase):
    print('{}{}'.format(letter, LETTER), end=' ')


aA bB cC dD eE fF gG hH iI jJ kK lL mM nN oO pP qQ rR sS tT uU vV wW xX yY zZ 

Recursion


In [7]:
def fact(n: int) -> int:
    if n <= 0:
        return 1
    return n * fact(n - 1)

In [8]:
for n in range(10):
    print("{}: fact:{}".format(n, fact(n)))


0: fact:1
1: fact:1
2: fact:2
3: fact:6
4: fact:24
5: fact:120
6: fact:720
7: fact:5040
8: fact:40320
9: fact:362880

In [9]:
def count(word: str, letter: str, start=0) -> int:
    if not word:
        return 0
    return (1 if word[start] == letter else 0) + count(word[start + 1:], letter, 0)

In [10]:
for letter in ascii_lowercase:
    print('{}:{}'.format(letter, count(ascii_lowercase, letter)), end=' ')


a:1 b:1 c:1 d:1 e:1 f:1 g:1 h:1 i:1 j:1 k:1 l:1 m:1 n:1 o:1 p:1 q:1 r:1 s:1 t:1 u:1 v:1 w:1 x:1 y:1 z:1 

In [11]:
from random import choice

start_at = choice(range(len(ascii_lowercase)))

for letter in ascii_lowercase:
    print('{}:{}'.format(letter, count(ascii_lowercase, letter, start_at)), end=' ')


a:0 b:0 c:0 d:0 e:0 f:0 g:0 h:0 i:0 j:0 k:0 l:0 m:0 n:0 o:0 p:0 q:0 r:0 s:0 t:0 u:0 v:0 w:1 x:1 y:1 z:1 

While Loop


In [12]:
value = 0

while value < 10:
    print(value)
    value += 1


0
1
2
3
4
5
6
7
8
9

In [13]:
value = choice(range(100))

print("Sequence to {}: ".format(value))
while True:
    if value == 1:
        break
    elif value % 2 == 0:
        value //= 2
    else:
        value = value * 3 + 1
        
    print(value, end=' ')


Sequence to 9: 
28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 

Expressões geradoras


In [14]:
g = (x**2 for x in range(5))
print(g)


<generator object <genexpr> at 0x7f07482d9f68>

In [15]:
print(next(g))


0

In [16]:
print(next(g))


1

In [17]:
for val in g:
    print(val)


4
9
16

In [18]:
#next(g)

#---------------------------------------------------------------------------
#StopIteration                             Traceback (most recent call last)
#<ipython-input-6-5f315c5de15b> in <module>()
#----> 1 next(g)
#
#StopIteration:

In [19]:
print(sum(x**2 for x in range(5)))


30

In [20]:
print(max(x**2 for x in range(5)))


16

In [21]:
print(min(x**2 for x in range(5)))


0